import { message, Modal } from '@bytedance/mona-ui';
import { createTaskId } from "@contents/jinritemaiCopyGoods/copyDataFomate"
import { getFlowInfo } from '@Api/toNewPageApi/clearNotFlow'
import { store } from "~store"
/**
 * 
 * @param {string} pageUrl
 */


class GetForPageData {
    constructor(options) {
        this.pageUrl = options.pageUrl || '';
        this.openUrl = options.openUrl || '';
        this.title = options.title || '';
        this.baseUrl = options.baseUrl || location.origin;
        this.timeout = options.timeout || 5000;
        this.tab_id = '';
        this.bodyinit = {
            baseUrl: options.baseUrl || location.origin,
            timeout: options.timeout || 5000,
            headers: options.headers || {},
        }
        this.requestmap = new Map();
        this.runOutTimeEnd = 4000 // 请求超时时间
        this.requterNum = 7 // 请求重试次数
        this.reuInfoCb = null
        this.shop_id = store.getState().jinritemaiShops?.userShopId || ''
    }
    async init(cb) {
        console.log('tore.getState().jinritemaiShops', store.getState().jinritemaiShops)
        const _this = this
        _this.reuInfoCb = cb
        _this.shop_id = store.getState().jinritemaiShops?.userShopId || ''
        const res = await cheackPageOpenStatus([_this.pageUrl]).catch((err) => {
            return err;
        })
        if (res.code === 200 && res.data.length > 0) {
            const openStatus = res.data.find((item) => item.status)
            if (openStatus) {
                _this.tab_id = openStatus.id;
                // 这里加一个
                const getInfoDatas = await _this.openReqU(getFlowInfo())
                console.log('检查店铺信息', getInfoDatas)
                if (getInfoDatas.code) {
                    const getAter = await _this.openCurlModal('电商罗盘登陆信息失效，关闭所有电商罗盘页面后重试')
                    // console.log('信息不一致, 需要重新打开页面')
                    _this.reuInfoCb && _this.reuInfoCb({
                        msg: '电商罗盘页面已打开',
                        type: 'success',
                        data: getAter
                    })
                    return true
                }
                if (!getInfoDatas.data || !getInfoDatas.data.account_id) {
                    const getAter = await _this.openCurlModal('电商罗盘与抖店信息不一致，关闭所有电商罗盘页面后重试')
                    _this.reuInfoCb && _this.reuInfoCb({
                        msg: '电商罗盘页面已打开',
                        type: 'success',
                        data: getAter
                    })
                    return true
                }
                if (getInfoDatas && !getInfoDatas.code && getInfoDatas.data.account_id !== _this.shop_id) {
                    const getAter = await _this.openCurlModal('电商罗盘与抖店信息不一致，关闭所有电商罗盘页面后重试')
                    // console.log('信息不一致, 需要重新打开页面')
                    _this.reuInfoCb && _this.reuInfoCb({
                        msg: '电商罗盘页面已打开',
                        type: 'success',
                        data: getAter
                    })
                    return true
                }
                return true
            }
            message.error(_this.title)

            const getAter = await _this.openCurlModal()
            // console.log('打开页面 获取用户详情的结构钢', getAter)
            // console.log('已经获取到用户的信息 开始匹配用户信息是否一致 -*-*', getAter.data.account_id, _this.shop_id)
            // console.log('getAter.data.account_id', getAter.data.account_id)
            // console.log('getAter.data.account_id', _this.shop_id)
            if (getAter && !getAter.code && getAter.data.account_id !== _this.shop_id) {
                _this.reuInfoCb && _this.reuInfoCb({
                    msg: '电商罗盘与抖店信息不一致，关闭所有电商罗盘页面后重试',
                    type: 'shopInfoNoter',
                    data: getAter
                })
                return false
            }
            _this.reuInfoCb && _this.reuInfoCb({
                msg: '电商罗盘页面已打开',
                type: 'success',
                data: getAter
            })
            return true
        }
    }
    open(body) {
        const _this = this

        const noewBOdy = { ..._this.bodyinit, ...body }


        let runTimeFuncs = null
        return new Promise((resolve, reject) => {
            if (!_this.tab_id) {
                reject('tab_id不存在')
                return
            }
            removeLententFuns('call_script_function_req')
            let createTaskIdStr = createTaskId()
            window.postMessage({
                type_urs: 'wtbg',
                type_page: 'pageMeat',
                method: 'call_script_function',
                tab_id: _this.tab_id,
                body: noewBOdy,
                createTaskIdStr
            })
            _this.requestmap.set(createTaskIdStr, {
                resolve,
                reject,
            })
            // window.addEventListener('message', this.getDatatest)
            addLententFuns('call_script_function_req', (e) => {
                const { type, method, createTaskIdStr } = e.data
                if (method === 'send_dly_all' && type === 'wt_bgRequest_topage') {
                    clearTimeout(runTimeFuncs)
                    runTimeFuncs = null
                    const getTask = _this.requestmap.get(createTaskIdStr)
                    if (getTask) {
                        getTask.resolve(e.data.data)
                        _this.requestmap.delete(createTaskIdStr)
                        return
                    }
                    resolve(e.data.data)
                }
            })
            runTimeFuncs = setTimeout(() => {
                clearTimeout(runTimeFuncs)
                runTimeFuncs = null
                removeLententFuns('call_script_function_req')
                _this.requestmap.delete(createTaskIdStr)
                reject('请求超时')
            }, body.runOutTimeEnd || _this.runOutTimeEnd)

        })
    }

    // 下面而外加的功能
    openCurlModal(text) {
        return new Promise(async (resolve, reject) => {
            const _this = this
            Modal.warning({
                title: '提示',
                content: text || _this.title,
                onOk(clear) {
                    _this.clear_all_page()
                    console.log('正在打开电商罗盘页面 -*-*')
                    _this.reuInfoCb && _this.reuInfoCb({
                        msg: '打开电商罗盘页面',
                        type: 'openPageing'
                    })
                    window.postMessage({
                        type_urs: 'wtbg',
                        url: _this.openUrl,
                        type_page: 'pageMeat',
                        method: 'create_url_page'
                    })
                    removeLententFuns('creted_open_urls')
                    addLententFuns('creted_open_urls', (e) => {
                        if (e.data && e.data.method === "send_dly_all" && e.data.type_urs === 'wtbg' && e.data.api === "create_url_page") {
                            if (e.data.data && e.data.data.code === 200) {
                                _this.tab_id = e.data.data.data.id
                                console.log('获取到了电商罗盘页面id -*-*', _this.tab_id)
                                _this.reuInfoCb && _this.reuInfoCb({
                                    msg: '正在打开电商罗盘页面，请稍等',
                                    type: 'openPageSuccess'
                                })
                                removeLententFuns('creted_open_urls')
                                setTimeout(async () => {
                                    let runStatuaNums = 0
                                    const getInfoDatas = await _this.openReqU(getFlowInfo())
                                    // console.log('打开之后获取的用户信息结果', getInfoDatas)
                                    resolve(getInfoDatas)
                                }, 3000)
                            }
                        }
                    })
                    clear && clear()
                },
            })
        })
    }
    async openReqU(body, num) {
        let resPonsUnm = num || 0
        const dataAlls = await this.open(body).catch((err) => {
            console.log('err', err)
            return false
        })
        resPonsUnm++
        if (!dataAlls) {
            return resPonsUnm < this.requterNum ? this.openReqU(body, resPonsUnm) : {
                code: 480,
                msg: '超出重试次数'
            }
        }
        // console.log('dataAlls', dataAlls)
        return dataAlls
    }

    clear_all_page() {
        console.log(' this.openUrl---', this.pageUrl)
        window.postMessage({
            type_urs: 'wtbg',
            url: this.pageUrl,
            type_page: 'pageMeat',
            method: 'close_all_page'
        })

    }


    // async getFlowuserInfo(cb) {
    //     const getInfoDatas = await this.open(getFlowInfo()).catch((err) => {
    //         console.log('err', err)
    //         return false
    //     })
    //     // console.log('打开之后获取的用户信息结果222', getInfoDatas)

    //     if (!getInfoDatas) {
    //         return cb && cb() ? this.getFlowuserInfo() : {
    //             msg: '超出重试次数'
    //         }
    //     }
    //     return getInfoDatas
    // }

}
let envents = new Map()
removeLententFuns('call_script_function_req')
removeLententFuns('creted_open_urls')
function addLententFuns(id, cb) {
    envents.set(id, cb)
    window.addEventListener('message', envents.get(id))
}
function removeLententFuns(id) {
    window.removeEventListener('message', envents.get(id))
    envents.delete(id)
}

export const cheackPageOpenStatus = async (urls) => {
    window.postMessage({
        type_urs: 'wtbg',
        data: urls || ['https://compass.jinritemai.com/'],
        type_page: 'pageMeat',
        method: 'check_url_open'
    })
    return new Promise((resolve, reject) => {
        removeLententFuns('check_url_open')
        addLententFuns('check_url_open', (e) => {
            if (e.data.type_urs === 'wtbg' && e.data.api === "check_url_open" && e.data.method == "send_dly_all") {
                resolve(e.data.data)
            }
        })
    })

}

export default GetForPageData;